<?php
/**
 * Created by PhpStorm.
 * User: Rei
 * Date: 16/5/7
 * Time: 20:31
 * Mail: rei@king.moe
 */

namespace Home\Model;

use Think\Model;

class SubscribeModel extends Model
{
    public function subscribe($uid, $tags){
        foreach($tags AS $tag){
            $this->add(array('uid'=>$uid, 'tid'=>$tag));
        }
    }

    //订阅&取消
    public function addSubscribe($tid, $action)
    {
        $uid = session('uid');
        switch($action){
            case 'subscribe':
                return $this->data(array('uid'=>$uid, 'tid'=>$tid))->add();
                break;
            case 'unset':
                return $this->where(array('uid'=>$uid, 'tid'=>$tid))->delete();
                break;
            default :
                break;
        }
        return false;
    }

    //获取订阅提醒
    public function getSubNotify(){
        $data = array();
        if(session('?uid')){
            $uid = session('uid');
            $time = time() - 3600*24*3;
            $data = $this->field("(select count(*) from pin_news where pin_news.topic = pin_subscribe.tid AND pubtime>$time) AS num, pin_subscribe.tid, name")
                 ->join('__TOPIC__ ON __TOPIC__.tid = __SUBSCRIBE__.tid', 'LEFT')
                 ->where("uid=$uid")
                 ->select();
        }
        return $data;
    }

    //获取热评文章
    public function getMostComment(){
        $data = array();
        if(session('?uid')){
            $uid = session('uid');
            $time = mondayTime();
            $data = $this->query("SELECT (SELECT count(*) FROM __COMMENT__ WHERE __COMMENT__.thread_key = __NEWS__.nid AND created_at > $time) AS num, __NEWS__.title, __NEWS__.nid FROM __NEWS__ LEFT JOIN __SUBSCRIBE__ ON __SUBSCRIBE__.tid = __NEWS__.topic WHERE __SUBSCRIBE__.uid = $uid");
            foreach ($data as $key => $row) {
                $num[$key] = $row['num'];
            }
            if(!empty($data)){
                array_multisort($num, SORT_DESC, $data);
                $data = $data[0];
            }
        }
        return $data;
    }

    //获取用户订阅信息
    public function getSubscribe(){
        $data = array();
        if(session('?uid')){
            $uid = session('uid');
            $data = $this->query("SELECT __TOPIC__.tid, __TOPIC__.name, (select count(uid) from __SUBSCRIBE__ where uid = $uid and tid=__TOPIC__.tid) AS isSub ,(Select count(*) from __SUBSCRIBE__ where tid=__TOPIC__.tid) AS num FROM __TOPIC__");
        }
        return $data;
    }

}